package com.hzsai.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzsai.dynamicdatasource.DataSourceKey;
import com.hzsai.dynamicdatasource.DynamicDS;
import com.hzsai.mappersc.AopUserMapper;
import com.hzsai.pojo.AopUser;
import com.hzsai.service.DynamicDSService;
import com.hzsai.utils.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * hzsai 2019/8/28
 * usage:
 **/
@Service
public class DynamicDSServiceImpl implements DynamicDSService {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDSServiceImpl.class);

    @Autowired
    private AopUserMapper mapper;

    @Override
    @DynamicDS(datasourceKey = DataSourceKey.THIRD)
    public AopUser selectById(Integer id) {
        AopUser user = mapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    @DynamicDS(datasourceKey = DataSourceKey.FIRST)
    public List<AopUser> selectUserPage(Map<String, Object> params) {
        int pageNow  = Integer.valueOf((String)params.get("pageNow"));
        int pageSize = Integer.valueOf((String)params.get("pageSize"));

        // startPage后面的第一个查询才有效，同时切记，一定要消耗产生的startpage
        PageHelper.startPage(pageNow, pageSize);
        List<AopUser> retList = (List)mapper.selectUserPage(null);

        // jdk8 lambda
        // Page<AopUser> page = PageHelper.startPage(pageNow, pageSize).doSelectPage(() -> mapper.selectUserPage(null));

        logger.debug("[selectUserPage]: {}", JSONUtil.toJSONString(retList));

        logger.debug("retList size: {}", retList.size());

        // 如果在这之间有做数据处理，需要小心
        // https://github.com/pagehelper/Mybatis-PageHelper/issues/417

        PageInfo<AopUser> info = new PageInfo<>(retList);
        logger.debug("[selectUserPage]: total: {}", info.getTotal());
        logger.debug("[selectUserPage]: page info{}", JSONUtil.toJSONString(info));

        return retList;
    }
}
